﻿using HookupAppForm.Dto;
using HookupAppForm.MyUserControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HookupAppForm
{
    public partial class FormSubmain : Form
    {
        private string url = "api/services/app/HKP_Submain/";
        private HKP_SubmainDto Item { get; set; }
        private APIClient Client { get; set; }
        private int X { get; set; }
        private int Y { get; set; }
        public FormSubmain(HKP_SubmainDto item, APIClient _client, int x = 0, int y = 0)
        {
            InitializeComponent();
            Item = item;
            Client = _client;
            X = x;
            Y = y;
        }

        private void FormSubmain_Load(object sender, EventArgs e)
        {
            ucDrpFlowUnit.Init("流量", Client.RemoteHost,0,"CMH");
            ucDrpPressureUnit.Init("压力单位", Client.RemoteHost,0,"Pa");
            ucDrpPowerUnit.Init("功率", Client.RemoteHost);
            BindCombSys();
            LoadData();
            SetItem(Item);
            ucDpdBuilding.Init("Building", Client.RemoteHost);
            ucDpdBuilding.selectedChangeEvent += new UserControlDropdown.SelectedChangeDelegate(UcDpdBuildingSelectedChange);
        }
        private void SetItem(HKP_SubmainDto Item)
        {
            if (Item != null)
            {
                numFlowAvg.Value = Item.FlowAvg;
                numFlowMin.Value = Item.FlowMin;
                numFlowPeak.Value = Item.FlowPeak;
                numFlowPeakOperation.Value = Item.FlowPeakOperation;
                numPressureAvg.Value = Item.PressureAvg;
                numPressureMin.Value = Item.PressureMin;
                numPressurePeak.Value = Item.PressurePeak;
                numPressurePeakOper.Value = Item.PressurePeakOper;
                numPower.Value = Item.Power;
                numPowerOper.Value = Item.PowerOper;
                numPowerAvg.Value = Item.PowerAvg;
                numPowerMin.Value = Item.PowerMin;
                txtRemark.Text = Item.Remark;
                txtSubmainName.Text = Item.SubmainName;
                txtSubmainNo.Text = Item.SubmainNo;
                //ES系统要赋值给下拉框
                if (Item.SystemId.ToString() == "ES")
                {
                    userdianya.selectedValue = Item.PressurePeak.ToString();
                }
                
                combSystemId.SelectedValue = Item.SystemId.ToString();
                ucDrpFlowUnit.SetText(Item.FlowUnit);
                ucDrpPressureUnit.SetText(Item.PressureUnit);
                ucDrpPowerUnit.SetText(Item.PowerUnit);
                numWidth.Value = Item.Width;
                numLength.Value = Item.Length;
                numX.Value = Item.X;
                numY.Value = Item.Y;
                ucDpdBuilding.SetText(Item.Building);
                ucDpdFloor.SetText(Item.Floor);
                numAllpoint.Value = Item.Allpoint;
                numusedpoint.Value = Item.usedpoint;
                numUsedFlow.Value = Item.numUsedFlow;
                userdianya.SetText(Item.PressurePeak.ToString());
            }
            else
            {
                numX.Value = X;
                numY.Value = Y;
            }
        }
        private void BindCombSys()
        {
            string url = string.Format("api/services/app/HKP_System/GetList?maxResultCount={0}", 9999);
            var result = Client.Get(url);
            ItemsDto<HKP_SystemDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_SystemDto>>(result);
            combSystemId.DataSource = dto?.result?.items;
            combSystemId.DisplayMember = "SysName";
            combSystemId.ValueMember = "Id";
            //combSystemId.SelectedIndex = -1;
        }
        private void LoadData()
        {
            string act = string.Format(url + "GetList");
            var result = Client.Get(act);
            ItemsDto<HKP_SubmainDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_SubmainDto>>(result);
            dataGridViewM.DataSource = res?.result?.items;
            FromSetting[] fromSettings = new FromSetting[29];
            fromSettings[1] = new FromSetting { FieldDisplay = "管道编号",FieldWidth = 150 };
            fromSettings[2] = new FromSetting { FieldDisplay = "管道名称",FieldWidth=150 };
            fromSettings[3] = new FromSetting { FieldDisplay = "设计（流量/容量）", FieldWidth = 120 };
            fromSettings[27] = new FromSetting { FieldDisplay = "接点总数", FieldWidth = 120 };
            fromSettings[28] = new FromSetting { FieldDisplay = "已用接点", FieldWidth = 120 };
            fromSettings[25] = new FromSetting { FieldDisplay = "所在厂房", FieldWidth = 120 };
            fromSettings[26] = new FromSetting { FieldDisplay = "所在楼层", FieldWidth = 120 };
            fromSettings[12] = new FromSetting { FieldDisplay = "压力单位/电源种类", FieldWidth = 120 };

            fromSettings[7] = new FromSetting { FieldDisplay = "流量单位", FieldWidth = 120 };
            fromSettings[8] = new FromSetting { FieldDisplay = "额定压力/电压（V）", FieldWidth = 120 };
            fromSettings[9] = new FromSetting { FieldDisplay = "操作压力负荷", FieldWidth = 120 };
            fromSettings[13] = new FromSetting { FieldDisplay = "设计功率负荷", FieldWidth = 120 };
            fromSettings[14] = new FromSetting { FieldDisplay = "操作功率负荷", FieldWidth = 120 };
            Utils.SetHeader(dataGridViewM, fromSettings);
        }

        private void SaveToolStripButton_Click(object sender, EventArgs e)
        {
           
            string act = Item == null ? "Create" : "Update";
            string result = string.Empty;
            if (Item != null)
            {
                Item.FlowAvg = numFlowAvg.Value;
                Item.FlowMin = numFlowMin.Value;
                Item.FlowPeak = numFlowPeak.Value;
                Item.FlowPeakOperation = numFlowPeakOperation.Value;
                Item.PressureAvg = numPressureAvg.Value;
                Item.PressureMin = numPressureMin.Value;

                if (combSystemId.Text?.ToString() == "ES")
                {
                    Item.PressurePeak = Convert.ToDecimal(userdianya.selectedText);//设计压力负荷，ES的时候存储电压
                }
                else
                {
                    Item.PressurePeak = numPressurePeak.Value;//设计压力负荷，ES的时候存储电压
                }

                
                Item.PressurePeakOper = numPressurePeakOper.Value;
                Item.Power = numPower.Value;
                Item.PowerOper = numPowerOper.Value;
                Item.PowerAvg = numPowerAvg.Value;
                Item.PowerMin = numPowerMin.Value;
                Item.Remark = txtRemark.Text;
                Item.SubmainName = txtSubmainName.Text;
                Item.SubmainNo = txtSubmainNo.Text;
                Item.SystemId = Guid.Parse(combSystemId.SelectedValue?.ToString());
                Item.PressureUnit = ucDrpPressureUnit.selectedText;
                Item.FlowUnit = ucDrpFlowUnit.selectedText;
                Item.PowerUnit = ucDrpPowerUnit.selectedText;
                Item.Width = numWidth.Value;
                Item.Length = numLength.Value;
                Item.X = numX.Value;
                Item.Y = numY.Value;
                Item.Building = ucDpdBuilding.selectedText;
                Item.Floor = ucDpdFloor.selectedText;
                Item.Allpoint = Convert.ToInt32(numAllpoint.Value);
                Item.Floor = ucDpdFloor.selectedText;
                Item.Allpoint = Convert.ToInt32(numAllpoint.Value);

                string jsons = JsonConvert.SerializeObject(Item);
                result = Client.Put(url + act, jsons);
            }
            else
            {
                CreateHKP_SubmainDto dto = new CreateHKP_SubmainDto();
                dto.FlowAvg = numFlowAvg.Value;
                dto.FlowMin = numFlowMin.Value;
                dto.FlowPeak = numFlowPeak.Value;
                dto.FlowPeakOperation = numFlowPeakOperation.Value;
                dto.PressureAvg = numPressureAvg.Value;
                dto.PressureMin = numPressureMin.Value;


                if (combSystemId.Text?.ToString() == "ES")
                {
                    dto.PressurePeak = Convert.ToDecimal(userdianya.selectedText);//设计压力负荷，ES的时候存储电压
                }
                else
                {
                    dto.PressurePeak = numPressurePeak.Value;//设计压力负荷，ES的时候存储电压
                }
                dto.PressurePeakOper = numPressurePeakOper.Value;
                dto.Power = numPower.Value;
                dto.PowerOper = numPowerOper.Value;
                dto.PowerAvg = numPowerAvg.Value;
                dto.PowerMin = numPowerMin.Value;
                dto.Remark = txtRemark.Text;
                dto.SubmainName = txtSubmainName.Text;
                dto.SubmainNo = txtSubmainNo.Text;
                dto.SystemId = Guid.Parse(combSystemId.SelectedValue?.ToString());
                dto.PressureUnit = ucDrpPressureUnit.selectedText;
                dto.FlowUnit = ucDrpFlowUnit.selectedText;
                dto.PowerUnit = ucDrpPowerUnit.selectedText;
                dto.Width = numWidth.Value;
                dto.Length = numLength.Value;
                dto.X = numX.Value;
                dto.Y = numY.Value;
                dto.Building = ucDpdBuilding.selectedText;
                dto.Floor = ucDpdFloor.selectedText;
                dto.Allpoint = Convert.ToInt32(numAllpoint.Value);


                string jsons = JsonConvert.SerializeObject(dto);
                result = Client.Post(url + act, jsons);
            }
            if (Utils.ExceptionHandler(result) == null)
            {
                Utils.SysMsg("保存成功！");
                var resp = Utils.SuccessHandler(result);
                Item = JsonConvert.DeserializeObject<HKP_SubmainDto>(resp.ToString());
                string keywords = txtGetListKeywords.Text.Trim();
                LoadDataSearch(keywords);
            }
        }

        private void DelToolStripButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除？", "系统", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                if (Item != null)
                {
                    string act = string.Format(url + "Delete?Id={0}", Item.Id);
                    string result = Client.Delete(act);
                    if (Utils.ExceptionHandler(result) == null)
                    {
                        LoadData();
                    }
                }
            }
        }

        private void CopyToolStripButton_Click(object sender, EventArgs e)
        {
            if (Item != null)
            {
                string act = url + "Create";
                string jsons = JsonConvert.SerializeObject(Item);
                string result = Client.Post(act, jsons);
                if (Utils.ExceptionHandler(result) == null)
                {
                    Utils.SysMsg("保存成功！");
                }

                string keywords = txtGetListKeywords.Text.Trim();
                LoadDataSearch(keywords);
            }
        }

        private void NewToolStripButton_Click(object sender, EventArgs e)
        {
            if (Item != null)
            {
                numFlowAvg.Value = 0;
                numFlowMin.Value =0;
                numFlowPeak.Value = 0;
                numFlowPeakOperation.Value = 0;
                numPressureAvg.Value = 0;
                numPressureMin.Value = 0;
                numPressurePeak.Value = 0;
                numPressurePeakOper.Value = 0;
                numusedpoint.Value = 0;//清空使用点数
                numAllpoint.Value = 0;//清空可用总点数
                txtRemark.Text = "";
                txtSubmainName.Text = "";
                txtSubmainNo.Text = "";

                ucDrpFlowUnit.SetText("");
                ucDrpPressureUnit.SetText("");
                ucDrpPowerUnit.SetText("");
                Item = null;
            }
        }

        private void DataGridViewM_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Item = dataGridViewM.CurrentRow.DataBoundItem as HKP_SubmainDto;
            SetItem(Item);
        }

        internal void SetLoc(int mouseDownX_Draw, int mouseDownY_Draw)
        {
            try
            {
                Invoke((ThreadStart)delegate
                {
                    numX.Value = mouseDownX_Draw;
                    numY.Value = mouseDownY_Draw;
                });
            }
            catch (Exception)
            {

            }
        }

        private void UcDpdBuildingSelectedChange(object sender, EventArgs e)
        {
            ucDpdFloor.Init("Building", Client.RemoteHost, Convert.ToInt32(ucDpdBuilding.selectedValue));
        }

      
        private void combSystemId_SelectedValueChanged(object sender, EventArgs e)
        {
            string x = Convert.ToString(this.combSystemId.DisplayMember);
            x = combSystemId.Text;
            if (x == "ES")
            {
                ucDrpFlowUnit.Init("容量", Client.RemoteHost);
                ucDrpPressureUnit.Init("电源种类", Client.RemoteHost,0,"N");
                userdianya.Init("电压", Client.RemoteHost, 0, "380");
                label8.Text = "电压(V)";
                label14.Text = "电源种类";
                label2.Text = "容量单位";

                userdianya.Visible = true;//放开电压选项

                numPressurePeak.Visible = false;
                //label9.Text = "";
                //label10.Text = "";
                //label11.Text = "";
                numPressurePeakOper.Enabled = false;
                numPressureAvg.Enabled = false;
                numPressureMin.Enabled = false;
            }
            else
            {
                ucDrpFlowUnit.Init("流量", Client.RemoteHost);
                ucDrpPressureUnit.Init("压力单位", Client.RemoteHost, 0, "Pa");
                label8.Text = "设计压力负荷";
                label14.Text = "压力单位";
                label2.Text = "流量单位";

                //label9.Text = "操作压力负荷";
                //label10.Text = "平均压力";
                //label11.Text = "最小压力";
                userdianya.Visible = false;//
                numPressurePeak.Visible = true;//放开设计压力负荷
                numPressurePeakOper.Enabled = true;
                numPressureAvg.Enabled = true;
                numPressureMin.Enabled = true;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string keywords = txtGetListKeywords.Text.Trim();
            if (string.IsNullOrEmpty(keywords))
            {
                Utils.SysMsg("请输入关键字！");
                return;
            }
            LoadDataSearch(keywords);

        }
        public void  LoadDataSearch(string keywords) 
        {
            string act = string.Format(url + "GetListKewords?GetListKewords={0}", keywords);
            var result = Client.Get(act);
            ItemsDto<HKP_SubmainDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_SubmainDto>>(result);
            dataGridViewM.DataSource = res?.result?.items;
            FromSetting[] fromSettings = new FromSetting[29];
            fromSettings[1] = new FromSetting { FieldDisplay = "管道编号", FieldWidth = 150 };
            fromSettings[2] = new FromSetting { FieldDisplay = "管道名称", FieldWidth = 150 };
            fromSettings[3] = new FromSetting { FieldDisplay = "设计（流量/容量）", FieldWidth = 120 };
            fromSettings[27] = new FromSetting { FieldDisplay = "接点总数", FieldWidth = 120 };
            fromSettings[28] = new FromSetting { FieldDisplay = "已用接点", FieldWidth = 120 };
            fromSettings[25] = new FromSetting { FieldDisplay = "所在厂房", FieldWidth = 120 };
            fromSettings[26] = new FromSetting { FieldDisplay = "所在楼层", FieldWidth = 120 };
            fromSettings[12] = new FromSetting { FieldDisplay = "压力单位/电源种类", FieldWidth = 120 };

            fromSettings[4] = new FromSetting { FieldDisplay = "操作流量负荷", FieldWidth = 120 };
            fromSettings[8] = new FromSetting { FieldDisplay = "额定压力/电压（V）", FieldWidth = 120 };
            fromSettings[9] = new FromSetting { FieldDisplay = "操作压力负荷", FieldWidth = 120 };
            fromSettings[13] = new FromSetting { FieldDisplay = "设计功率负荷", FieldWidth = 120 };
            fromSettings[14] = new FromSetting { FieldDisplay = "操作功率负荷", FieldWidth = 120 };
            Utils.SetHeader(dataGridViewM, fromSettings);

        }
    }
}
